package com.ycwl.freetv;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;


import com.ycwl.freetv.receiver.UsbReceiver;
import com.ycwl.freetv.utils.FileUtils;
import com.ycwl.freetv.utils.SystemUtils;
import com.ycwl.library.AssetsListManager;
import com.ycwl.library.Utils;

import java.io.File;
import java.io.IOException;
import java.security.Permission;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseActivity extends AppCompatActivity {
    static String TAG = "BaseActivity";
    public static Activity content;
    public static String usbPath = null;
    final class Cmd {
        public static final int usbMount = 1;
        public static final int copySource = 2;
        public static final int copyOver = 3;
        public static final int unzipFail = 4;
        public static final int storageSpaceNotEnough = 5;
    }
    protected static AutoUpdater  autoUpdater;
    public static boolean hasPermission = false;
    UsbReceiver usbReceiver;
    boolean usbReceiverIsRegister = false;
    protected final Handler broadcastHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String strmg = "";
            switch (msg.what) {
                case Cmd.usbMount:
                    strmg = "发现存储设备,正在扫描...";
                    break;
                case Cmd.copySource:
                    strmg = "正在进行数据备份,请不要拔出存储设备...";
                    break;
                case Cmd.copyOver:
                    strmg = "数据备份完成，可以拔出设备";
                    break;
                case Cmd.unzipFail:
                    strmg = "资源解压失败";
                    break;
                case Cmd.storageSpaceNotEnough:
                    strmg = "磁盘空间不足,无法备份";
                    break;
                default: {
                    strmg = "未知消息";
                    if (msg.obj != null) {
                        strmg = (String)msg.obj;
                    }
                }
            }
            Toast.makeText(getApplicationContext(), strmg, Toast.LENGTH_LONG).show();
        }
    };

    public boolean hasAutoStartPermission() {
        PowerManager powerManager = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return true;
    }

    protected void checkUpdateApk() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1000;
                message.obj = new String("正在从U盘中检查APP更新,请勿拔出U盘");
                broadcastHandler.sendMessage(message);
                File file = new File(usbPath);
                if (file.exists() && file.isDirectory()) {
                    autoUpdater.checkUpdateFromUsb(usbPath);
                }
            }
        }).start();
    }
    public void OnUsbMount(String path) {
        usbPath = path;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},10);
        } else {
            checkUpdateApk();
        }
        onUsbReady(path);
    }

    public BaseActivity() {
        super();
        usbReceiver = new UsbReceiver(this);
        autoUpdater = new AutoUpdater(this);
    }

    public void onUsbDetached(UsbDevice usbDevice) {
        Log.d(TAG, "onUsbDetached");
    }

    public void sendMessage(Message message) {

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        usbReceiver.register(this);

        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        String[] permissionArray =  permissionList.toArray(new String[0]);
        if (permissionArray.length > 0) {
            Log.d(TAG,"permission request");
            for(String str: permissionList) {
                Log.d(TAG,"permission request :" + str);
            }
            ActivityCompat.requestPermissions(this, permissionArray,1);
        }

        // 后台启动权限申请
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:"+getPackageName()));
                startActivity(intent);
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent1 = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivity(intent1 );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG,"permission request reault:"+requestCode);
        boolean isRequestOk = true;
        for (int i=0;i< permissions.length;i++) {
            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG,"permission "+permissions[i]+"; result: 允许");
            } else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                Log.d(TAG,"permission "+permissions[i]+"; result: 拒绝");
                isRequestOk = false;
            } else {
                Log.d(TAG,"permission "+permissions[i]+"; result:"+grantResults[i]);
            }
        }
        // 扩展内存申请
        if (requestCode == 10 && isRequestOk) {
            checkUpdateApk();
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        usbReceiver.unRegister(this);
    }

    protected abstract void onUsbReady(String path);

}